package com.docmgmt.mvp.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.docmgmt.mvp.dto.AddGroupMembersRequest;
import com.docmgmt.mvp.dto.CreateUserGroupRequest;
import com.docmgmt.mvp.dto.UserGroupVO;
import com.docmgmt.mvp.entity.UserEntity;
import com.docmgmt.mvp.entity.UserGroupEntity;
import com.docmgmt.mvp.entity.UserGroupMemberEntity;
import com.docmgmt.mvp.exception.BusinessException;
import com.docmgmt.mvp.exception.ForbiddenException;
import com.docmgmt.mvp.mapper.UserGroupMapper;
import com.docmgmt.mvp.mapper.UserGroupMemberMapper;
import com.docmgmt.mvp.mapper.UserMapper;
import com.docmgmt.mvp.service.UserGroupService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 用户组服务实现（USER-006）
 *
 * @author Dora
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserGroupServiceImpl extends ServiceImpl<UserGroupMapper, UserGroupEntity> implements UserGroupService {

    private final UserGroupMapper groupMapper;
    private final UserGroupMemberMapper memberMapper;
    private final UserMapper userMapper;

    /**
     * 创建用户组
     */
    @Transactional
    public UserGroupVO createGroup(CreateUserGroupRequest request, Long creatorId) {
        log.info("创建用户组：name={}, creatorId={}", request.getName(), creatorId);

        // 1. 创建用户组
        UserGroupEntity group = new UserGroupEntity();
        group.setName(request.getName());
        group.setDescription(request.getDescription());
        group.setOwnerId(creatorId);
        group.setCreatedAt(LocalDateTime.now());
        group.setUpdatedAt(LocalDateTime.now());

        groupMapper.insert(group);

        // 重新查询获取完整数据（包含数据库自动填充的timestamp）
        group = groupMapper.selectById(group.getId());

        // 2. 添加创建人为owner
        UserGroupMemberEntity ownerMember = new UserGroupMemberEntity();
        ownerMember.setGroupId(group.getId());
        ownerMember.setUserId(creatorId);
        ownerMember.setRole("owner");
        ownerMember.setCreatedAt(LocalDateTime.now());

        memberMapper.insert(ownerMember);

        // 3. 添加初始成员
        int memberCount = 1; // owner
        if (request.getInitialMemberIds() != null && !request.getInitialMemberIds().isEmpty()) {
            for (Long userId : request.getInitialMemberIds()) {
                if (!userId.equals(creatorId)) { // 跳过owner
                    UserGroupMemberEntity member = new UserGroupMemberEntity();
                    member.setGroupId(group.getId());
                    member.setUserId(userId);
                    member.setRole("member");
                    member.setCreatedAt(LocalDateTime.now());

                    memberMapper.insert(member);
                    memberCount++;
                }
            }
        }

        log.info("用户组创建成功：groupId={}, memberCount={}", group.getId(), memberCount);

        // 4. 构建返回VO
        UserEntity creator = userMapper.selectById(creatorId);
        return UserGroupVO.builder()
                .id(group.getId())
                .name(group.getName())
                .description(group.getDescription())
                .ownerId(creatorId)
                .ownerName(creator != null ? creator.getUsername() : "Unknown")
                .memberCount(memberCount)
                .myRole("owner")
                .createdAt(group.getCreatedAt())
                .updatedAt(group.getUpdatedAt())
                .build();
    }

    /**
     * 查询用户的用户组列表
     */
    public List<UserGroupVO> listUserGroups(Long userId) {
        log.debug("查询用户组列表：userId={}", userId);

        // 查询用户是成员的所有组
        LambdaQueryWrapper<UserGroupMemberEntity> memberQuery = new LambdaQueryWrapper<>();
        memberQuery.eq(UserGroupMemberEntity::getUserId, userId);

        List<UserGroupMemberEntity> memberships = memberMapper.selectList(memberQuery);
        if (memberships.isEmpty()) {
            return new ArrayList<>();
        }

        // 获取组ID和角色映射
        Map<Long, String> groupRoles = memberships.stream()
                .collect(Collectors.toMap(
                        UserGroupMemberEntity::getGroupId,
                        UserGroupMemberEntity::getRole
                ));

        // 查询组信息
        List<Long> groupIds = new ArrayList<>(groupRoles.keySet());
        List<UserGroupEntity> groups = groupMapper.selectBatchIds(groupIds);

        // 构建VO列表
        List<UserGroupVO> result = new ArrayList<>();
        for (UserGroupEntity group : groups) {
            // 统计成员数
            LambdaQueryWrapper<UserGroupMemberEntity> countQuery = new LambdaQueryWrapper<>();
            countQuery.eq(UserGroupMemberEntity::getGroupId, group.getId());
            Long memberCount = memberMapper.selectCount(countQuery);

            // 获取owner信息
            UserEntity owner = userMapper.selectById(group.getOwnerId());

            result.add(UserGroupVO.builder()
                    .id(group.getId())
                    .name(group.getName())
                    .description(group.getDescription())
                    .ownerId(group.getOwnerId())
                    .ownerName(owner != null ? owner.getUsername() : "Unknown")
                    .memberCount(memberCount.intValue())
                    .myRole(groupRoles.get(group.getId()))
                    .createdAt(group.getCreatedAt())
                    .updatedAt(group.getUpdatedAt())
                    .build());
        }

        return result;
    }

    /**
     * 添加成员到用户组
     */
    @Transactional
    public void addMembers(Long groupId, AddGroupMembersRequest request, Long operatorId) {
        log.info("添加成员到用户组：groupId={}, userIds={}, operatorId={}",
                groupId, request.getUserIds(), operatorId);

        // 1. 权限检查：必须是owner或admin
        String operatorRole = getMemberRole(groupId, operatorId);
        if (operatorRole == null || "member".equals(operatorRole)) {
            throw new ForbiddenException("无权限添加成员");
        }

        // 2. 批量添加成员
        int addedCount = 0;
        for (Long userId : request.getUserIds()) {
            // 检查用户是否存在
            UserEntity user = userMapper.selectById(userId);
            if (user == null) {
                log.warn("用户不存在，跳过：userId={}", userId);
                continue;
            }

            // 检查是否已是成员
            LambdaQueryWrapper<UserGroupMemberEntity> checkQuery = new LambdaQueryWrapper<>();
            checkQuery.eq(UserGroupMemberEntity::getGroupId, groupId)
                    .eq(UserGroupMemberEntity::getUserId, userId);

            if (memberMapper.selectCount(checkQuery) > 0) {
                log.warn("用户已是成员，跳过：userId={}", userId);
                continue;
            }

            // 添加成员
            UserGroupMemberEntity member = new UserGroupMemberEntity();
            member.setGroupId(groupId);
            member.setUserId(userId);
            member.setRole(request.getRole() != null ? request.getRole() : "member");
            member.setCreatedAt(LocalDateTime.now());

            memberMapper.insert(member);
            addedCount++;
        }

        log.info("成员添加完成：groupId={}, addedCount={}", groupId, addedCount);
    }

    /**
     * 移除成员
     */
    @Transactional
    public void removeMember(Long groupId, Long userId, Long operatorId) {
        log.info("移除用户组成员：groupId={}, userId={}, operatorId={}", groupId, userId, operatorId);

        // 1. 权限检查
        String operatorRole = getMemberRole(groupId, operatorId);
        String targetRole = getMemberRole(groupId, userId);

        // owner不能被移除
        if ("owner".equals(targetRole)) {
            throw new BusinessException("不能移除组的所有者");
        }

        // 只有owner/admin可以移除其他成员，或者成员可以移除自己
        boolean canRemove = "owner".equals(operatorRole) ||
                "admin".equals(operatorRole) ||
                userId.equals(operatorId);

        if (!canRemove) {
            throw new ForbiddenException("无权限移除此成员");
        }

        // 2. 删除成员记录
        LambdaQueryWrapper<UserGroupMemberEntity> deleteQuery = new LambdaQueryWrapper<>();
        deleteQuery.eq(UserGroupMemberEntity::getGroupId, groupId)
                .eq(UserGroupMemberEntity::getUserId, userId);

        int deleted = memberMapper.delete(deleteQuery);
        if (deleted == 0) {
            throw new BusinessException("成员不存在或已被移除");
        }

        log.info("成员移除成功：groupId={}, userId={}", groupId, userId);
    }

    /**
     * 删除用户组
     */
    @Transactional
    public void deleteGroup(Long groupId, Long operatorId) {
        log.info("删除用户组：groupId={}, operatorId={}", groupId, operatorId);

        // 1. 权限检查：仅owner可删除
        UserGroupEntity group = groupMapper.selectById(groupId);
        if (group == null) {
            throw new BusinessException("用户组不存在");
        }

        if (!group.getOwnerId().equals(operatorId)) {
            throw new ForbiddenException("仅组所有者可删除用户组");
        }

        // 2. 删除所有成员记录
        LambdaQueryWrapper<UserGroupMemberEntity> deleteMembersQuery = new LambdaQueryWrapper<>();
        deleteMembersQuery.eq(UserGroupMemberEntity::getGroupId, groupId);
        memberMapper.delete(deleteMembersQuery);

        // 3. 删除用户组
        groupMapper.deleteById(groupId);

        log.info("用户组删除成功：groupId={}", groupId);
    }

    /**
     * 获取用户在组中的角色
     */
    private String getMemberRole(Long groupId, Long userId) {
        LambdaQueryWrapper<UserGroupMemberEntity> query = new LambdaQueryWrapper<>();
        query.eq(UserGroupMemberEntity::getGroupId, groupId)
                .eq(UserGroupMemberEntity::getUserId, userId);

        UserGroupMemberEntity member = memberMapper.selectOne(query);
        return member != null ? member.getRole() : null;
    }
}
